package com.loyal.client.server;

import androidx.annotation.NonNull;

import com.loyal.client.RetroCallManager;
import com.loyal.client.ClientConfig;

import java.io.IOException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Retrofit2+OkHttp
 */
public abstract class BasicCallSubscriber<T> extends BasicSubscriberImpl<T, RetroCallManager> implements Callback<T> {
    private Call<T> call;

    @NonNull
    @Override
    protected RetroCallManager manager() {
        return RetroCallManager.getInstance();
    }

    public BasicCallSubscriber() {
        super();
    }

    public BasicCallSubscriber(@NonNull ClientConfig config) {
        super(config);
    }

    @Override
    public void onResponse(@NonNull Call<T> call, @NonNull Response<T> response) {
        this.call = call;
        if (response.isSuccessful()) {
            T t = response.body();
            if (null == t) {
                onError(new IOException("the response.body() is null!"));
            } else
                onNext(t);
            onComplete();
        } else {
            onError(new IOException(response.message()));
        }
    }

    @Override
    public void onFailure(@NonNull Call<T> call, @NonNull Throwable t) {
        this.call = call;
        onError(t);
    }

    @Override
    public void dispose() {
        if (null != call && !call.isCanceled())
            call.cancel();
    }

}
